<template>
  <textarea
    :id='id'
    :value='value'
  ></textarea>
</template>

<script>
// Import TinyMCE
import tinymce from 'tinymce/tinymce'
import 'tinymce/themes/modern/theme'
import 'tinymce/plugins/advlist'
import 'tinymce/plugins/link'
import 'tinymce/plugins/image'
import 'tinymce/plugins/code'
import 'tinymce/plugins/table'
import 'tinymce/plugins/textcolor'
import 'tinymce/plugins/paste'
import 'tinymce/plugins/colorpicker'
import ComponentApi from "@/api/components/component";

const INIT = 0
const CHANGED = 2
// var EDITOR = null
export default {
  props: {
    value: {
      type: String,
      editor: null,
      required: true
    },
    setting: {},
    url: {
      // 接口
      default: '',
      type: String
    },
    accept: {
      // 文件类型
      default: 'image/jpeg, image/png',
      type: String
    },
    maxSize: {
      // 大小
      default: 2097152,
      type: Number
    },
    withCredentials: {
      default: false,
      type: Boolean
    }
  },
  watch: {
    value: function (val) {
      // console.log('init ' + val)
      if (this.status === INIT || tinymce.activeEditor.getContent() !== val) {
        // 当状态等于 init 或者 编辑器内容为空时
        tinymce.activeEditor.setContent(val)
        // 就把编辑内容定位 传过来的value
      }
      this.status = CHANGED
      // 后把状态修改为changed
    }
  },
  data () {
    return {
      status: INIT,
      id: 'editor-' + new Date().getMilliseconds()
      // getMilliseconds() ：根据当地时间返回时间的毫秒
    }
  },
  methods: {
    handleFile (blobInfo, success, failure) {
      const _this = this
      ComponentApi.uploadOssApi()
        .then(res => {
          let OSS = require('ali-oss')
          let client = new OSS({
            region: _this.$Config.oss.region,
            accessKeyId: res.data.accessKeyId,
            accessKeySecret: res.data.accessKeySecret,
            stsToken: res.data.securityToken,
            bucket: _this.$Config.oss.bucket
          })
        // //debugger
        const file = blobInfo.blob()
        const fileName = blobInfo.filename();
        const fileType = fileName.split("\.")[1];
        let fileTempName = new Date().getTime() + fileName.split("\.")[0];
        if (fileTempName.length > 5){
          fileTempName = fileTempName.substring(0,12);
        }
        const newName = fileTempName +"."+ fileType;
        const storeAs = 'web_images/Editor/' + newName
        console.log('handleFile editor>>>>>' + fileName)
        // const json = { 'location': 'http://localhost:8008/static/img/logo.png' }
        // success({ 'location': '/static/img/logo.png' })
        // 个性化img标签
        //  抛出 'on-upload-success' 钩子
        // _this.$emit('on-upload-success', [
        //   json, success, failure
        // ])
        // TODO:For test
        // success('http://localhost:8008/static/img/logo.png')
        // 测试数据 暂注释上传动作
        client
          .put(storeAs, file, {})
          .then(function (r1) {
            let realUrl = r1.url.replace(_this.$Config.oss.ossUrl,_this.$Config.oss.realUrl);
            console.log('r1.url>>>>>' + realUrl)
            success(realUrl)
          })
          .catch(function (err) {
            console.error(err)
            failure(err)
          })
      })
    }
  },
  mounted () {
    const _this = this
    console.log('_this.id>>>>>>>' + _this.id)
    const setting = {  // 配置富文本编辑器高度等基本属性
      selector: '#' + _this.id,
      min_height: 360,
      menubar: false,
      skin_url: '/static/tinymce/skins/lightgray',
      language_url: '/static/tinymce/langs/zh_CN.js',
      language: 'zh_CN',
      branding: false,
      // TODO:ali-oss upload
      upload_image_url: this.$Config.api.uploadOssApi, // 配置的上传图片的路由
      automatic_uploads: false,
      init_instance_callback: function (editor) {
        // EDITOR = editor
        // console.log('Editor: ' + editor.id + ' is now initialized.')
        editor.on('input change undo redo', () => {
          var content = editor.getContent()
          _this.$emit('show', content) // 获取内容并把它传给父组件
        })
      },
      content_style: `
    *                         { padding:0; margin:0; }
    html, body                { height:100%; }
    img                       { max-width:100%; display:block;height:auto; }
    a                         { text-decoration: none; }
    iframe                    { width: 100%; }
    p                         { line-height:1.6; margin: 0px; }
    table                     { word-wrap:break-word; word-break:break-all; max-width:100%; border:none; border-color:#999; }
    .mce-object-iframe        { width:100%; box-sizing:border-box; margin:0; padding:0; }
    ul,ol                     { list-style-position:inside; }
  `,
      insert_button_items: 'image link | inserttable',
      paste_retain_style_properties: 'all',
      paste_word_valid_elements: '*[*]', // word需要它
      paste_data_images: true, // 粘贴的同时能把内容里的图片自动上传，非常强力的功能
      paste_convert_word_fake_lists: false, // 插入word文档需要该属性
      paste_webkit_styles: 'all',
      paste_merge_formats: true,
      nonbreaking_force_tab: false,
      paste_auto_cleanup_on_paste: false,
      plugins: [
        'advlist link image',
        'code',
        'table textcolor paste textcolor colorpicker'
      ], // 配置
      toolbar_items_size: 'small',
      block_formats:
        'Paragraph=p;Heading 1=h1;Heading 2=h2;Heading 3=h3;Heading 4=h4;Heading 5=h5;Heading 6=h6;',
      // toolbar1:
      //   'table | link unlink | uploadimg image media', // 工具栏1
      toolbar:
        'insertfile undo redo | uploadimg image media | formatselect | fontsizeselect | forecolor backcolor | fontselect bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | outdent indent | removeformat', // 工具栏2
      // 图片上传
      images_upload_handler: function (blobInfo, success, failure) {
        // TODO:
          // failure(blobInfo)
          // _this.$emit('on-ready', blobInfo.blob().size, blobInfo.blob())
        if (blobInfo.blob().size > _this.maxSize) {
          failure('文件体积过大')
        }
        if (_this.accept.indexOf(blobInfo.blob().type) >= 0) {
          //  indexof 返回某个指定的字符串值在字符串中首次出现的位置
          // uploadPic()
          console.log('blobInfo>>>>>>' + blobInfo.filename())

          // //debugger
          // const xhr = new XMLHttpRequest()

          // const formData = new FormData()

          _this.handleFile(blobInfo, success, failure)
          console.log('images_upload_handler>>>>>>')

          // formData.append('file', blobInfo.blob(), blobInfo.filename())
          // xhr.send(formData)
        } else {
          failure('图片格式错误')
        }

          // function uploadPic () { // 发送请求
          //   const xhr = new XMLHttpRequest()
          //   const formData = new FormData()
          //   xhr.withCredentials = _this.withCredentials
          //   xhr.open('POST', _this.url)
          //   xhr.onload = function () {
          //     failure('上传---' + xhr.status)
          //     if (xhr.status !== 200) {
          //       // 抛出 'on-upload-fail' 钩子
          //       _this.$emit('on-upload-fail')
          //       failure('上传失败: ' + xhr.status)
          //       return
          //     }
          //     const json = JSON.parse(xhr.responseText)
          //     // 抛出 'on-upload-success' 钩子
          //     _this.$emit('on-upload-success', [
          //       json, success, failure
          //     ])
          //   }
          //   xhr.onerror = function () {
          //     _this.$emit('on-ready', '上传失败')
          //   }
          //   formData.append('file', blobInfo.blob())
          //   xhr.send(formData)
          // }
      }
    }
    Object.assign(setting, _this.setting)

    tinymce.init(setting)
  },
  beforeDestroy: function () {
    if (this.id) {
      tinymce.get(this.id).destroy()
    }
  }
}
</script>
